package com.cloudlead.web.resource;

import com.cloudlead.common.lang.utils.ExceptionHelper;
import com.cloudlead.common.lang.api.ErrorActionResponse;
import com.cloudlead.common.lang.api.SimpleActionResponse;
import com.cloudlead.common.lang.utils.ObjectId;
import com.cloudlead.service.FileUploadService;
import com.cloudlead.utils.oss.FileContent;
import org.apache.http.HttpResponse;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.util.List;
import java.util.Random;

/**
 * Created by Dean on 2015/4/30.
 */
@Controller
@Path("/file")
@Produces(MediaType.APPLICATION_JSON)
public class FileController {

    @Inject
    private FileUploadService fileUploadService;

    @Context
    private HttpServletRequest request;

    @Context
    HttpServletResponse response;

    @GET
    @Path("/list")
    public Response listFile(@QueryParam("path") String path) {
        try {
            List<String> listFile = fileUploadService.listFile(path);
            return Response.ok().entity(new SimpleActionResponse<>(listFile)).build();
        } catch (Exception e) {
            e.printStackTrace();
            ErrorActionResponse response = ExceptionHelper.toResponse(e);
            throw new WebApplicationException(e.getMessage(), e, response.getCode());
        }
    }

    @GET
    @Path("/address")
    public Response getAddress(@QueryParam("key") String key) {
        try {
            String address = fileUploadService.getAddress(key);
            return Response.ok().entity(new SimpleActionResponse<>(address)).build();
        } catch (Exception e) {
            e.printStackTrace();
            ErrorActionResponse response = ExceptionHelper.toResponse(e);
            throw new WebApplicationException(e.getMessage(), e, response.getCode());
        }
    }

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("path") String path,
                               @FormDataParam("fileName") String fileName,
                               @FormDataParam("file") InputStream file,
                               @FormDataParam("file") FormDataContentDisposition fileDisposition) {
        try {
            if (null == fileName || "".equals(fileName)) {
                String fileName_ = fileDisposition.getFileName();
                fileName = ObjectId.get() + fileName_.substring(fileName_.lastIndexOf("."));
            }
            int contentLength = request.getContentLength();//TODO:临时方式，这个不准确，包括了其他请求参数的字节数
            String key = fileUploadService.uploadFile(path, fileName, contentLength, file);
            return Response.ok().entity(new SimpleActionResponse<>(key)).build();
        } catch (Exception e) {
            e.printStackTrace();
            ErrorActionResponse response = ExceptionHelper.toResponse(e);
            throw new WebApplicationException(e.getMessage(), e, response.getCode());
        }
    }

    @POST
    @Path("/newUpload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response newUploadFile(@FormDataParam("file") InputStream file ,
                                  @FormDataParam("col") String col,
                                  @FormDataParam("fileName") String fileName) {
        String path="";//路径


        String str = getRandomString(10);//随机10位字符
        System.out.println(str+"***********************"+col);

        if(fileName!=null&&!"".equals(fileName)){
            path=fileName;
        }else{
            path="E:/"+col+"/"+str+".jpg";
        }

        String result=storager(file,path);//获取返回结果


            try {
                response.getWriter().write("<meta http-equiv=\"content-type\"content=\"text/html;  charset=UTF-8\">");
                response.setCharacterEncoding("utf-8");
                if (result=="上传成功") {
                    response.getWriter().println("<script>alert(\"" + path + "====================\"); " +
                        "window.parent.document.getElementById(\"" + col + "\").value=\""+path+"\"; //获取父中DOM对象 " +
                            "</script>");

                }else {
                    response.getWriter().println("<script>alert(\"======="+result+"=============\"); </script>");

                }


            } catch (IOException e) {
                e.printStackTrace();
            }

            return Response.ok().build();



    }
    private String  storager( InputStream file,String path){

        try {
            System.out.print(file+"===================");

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=file.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            file.close();

            //把outStream里的数据写入内存
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = outStream.toByteArray();
            //new一个文件对象用来保存图片，默认保存当前工程根目录

            File imageFile = new File(path);
            //创建输出流
            FileOutputStream fileOutStream = new FileOutputStream(imageFile);
            //写入数据
            fileOutStream .write(data);
            outStream.close();
            fileOutStream.close();
            return "上传成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    @GET
    @Path("/download")
    public Response downloadFile(@QueryParam("key") String key) {
        int lastIndexOf = key.lastIndexOf("/");
        String fileName = key.substring(lastIndexOf + 1);
        FileContent fileContent = fileUploadService.downloadFile(key);
        return Response.ok().header("Content-Disposition", "attachment;filename=" + fileName).
                header("Content-Length", fileContent.getContentLength()).
                entity(fileContent.getContent()).build();
    }

}
